#include <stdio.h>
#include <string.h>
#include <omnetpp.h>
#include "TicTocMsg_m.h"

class TicToc : public cSimpleModule
{
  protected:
    virtual void forwardMessage(TicTocMsg *msg);
    virtual void initialize();
    virtual void handleMessage(cMessage *msg);
    virtual TicTocMsg *generateMessage();

  private:
    cMessage *event;
};


Define_Module(TicToc);

void TicToc::initialize()
{
    event = new cMessage("event");
    if (getIndex()==0)
    {
        TicTocMsg *msg = generateMessage();
        scheduleAt(0.0, msg);
    }
}
TicTocMsg * TicToc::generateMessage(){

    int n = size();
    int src  = getIndex();
    int dest = uniform (0,n-2);
    if(dest>=src) dest++;

    char msgname[20];

    sprintf(msgname, "tic-%d", getIndex());

    TicTocMsg *tmsg = new TicTocMsg(msgname);
    tmsg->setSource(src);
    tmsg->setDestination(dest);
    return tmsg;
}

void TicToc::handleMessage(cMessage *msg)
{



    int rand = uniform (0,10);

    if (rand<2)
    {
               EV << "\"Losing\" message\n";
               delete msg;
    }

    if (rand<5){
        scheduleAt(simTime()+2.0, event);
        bubble ("New Msg Created");
        EV << "EVENT created!";
    }
   if(msg==event)
     {

        EV << "Generating another message: ";
               TicTocMsg *newmsg = generateMessage();
               EV << newmsg << endl;
               forwardMessage(newmsg);
    }
   else{
       TicTocMsg *tmsg = check_and_cast<TicTocMsg *>(msg);
    if (tmsg->getDestination()==getIndex()){

        // Message arrived.
        EV << "Message " << msg << " arrived.\n";
        bubble("FERTIG JUNGE!");
        delete tmsg;
        EV << "Generating another message: ";
        TicTocMsg *newmsg = generateMessage();
        EV << newmsg << endl;
        bubble("Nagut einer geht noch :)");
        forwardMessage(newmsg);

    }
    else
    {
        // We need to forward the message.
       forwardMessage(tmsg);
    }
   }
}

void TicToc::forwardMessage(TicTocMsg *msg)
{
    // In this example, we just pick a random gate to send it on.
    // We draw a random number between 0 and the size of gate `out[]'.
    int n = gateSize("gate");
    int k = intuniform(0,n-1);

    msg->setHopCount(msg->getHopCount()+1);

    EV << "Forwarding message " << msg << " on gate inout[" << k << "]\n";
    send(msg, "gate$o", k);
}


